package org.stvd.controller.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.security.support.MethodSecurityMetadataSource;
import org.stvd.common.security.support.UrlSecurityMetadataSource;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.StringUtil;
import org.stvd.core.util.convert.PyCode;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Resources;
import org.stvd.entities.admin.Roles;
import org.stvd.entities.admin.Users;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.ResourcesService;
import org.stvd.service.admin.RolesService;
import org.stvd.service.admin.UsersService;

/**
 * @Title: CommonController
 * @Description: 公共控制类
 * @author houzx
 * @date 2020年7月27日
 */
@Controller
public class CommonController extends BaseController {

    @Autowired
    private ResourcesService resourcesService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping(value = "/common/csrf403")
    public String csrf403PageLoad(HttpServletRequest request, ModelMap map) {
        return "/common/csrf403.html";
    }
    
    @RequestMapping(value = "/common/error403")
    public String error403PageLoad(HttpServletRequest request, ModelMap map) {
        return "/common/error403.html";
    }

    @RequestMapping(value = "/common/error404")
    public String error404PageLoad(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
        return "/common/error404.html";
    }

    @RequestMapping(value = "/common/error500")
    public String error500PageLoad(HttpServletRequest request, ModelMap map) {
        return "/common/error500.html";
    }

    /**
     * 重新加载资源权限信息
     */
    @RequestMapping(value = "/admin/reloadresources", method = RequestMethod.POST)
    @ResponseBody
    public InterfaceResult<Map<String, Object>> reloadresources(HttpServletResponse response) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            // URL
            Map<String, Collection<ConfigAttribute>> urlMap = getResourceMap("URL");
            Collection<ConfigAttribute> configConsts = new ArrayList<ConfigAttribute>();
            ConfigAttribute configConst = new SecurityConfig("ROLE_ANONYMOUS");
            configConsts.add(configConst);
            urlMap.put("/login", configConsts);
            UrlSecurityMetadataSource.setResourceMap(urlMap);
            // METHOD
            MethodSecurityMetadataSource.setResourceMap(getResourceMap("METHOD"));
            result.setMsg("资源重载成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError(e.getMessage());
        }
        return result;
    }
    
    public Map<String, Collection<ConfigAttribute>> getResourceMap(String resourceType) {
        HashMap<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
        List<Resources> resources = this.resourcesService.findResourcesByType(resourceType, Consts.GUID);
        for (Resources resource : resources) {
            Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
            List<Roles> roleList = rolesService.getRolesByResId(resource.getResId());
            for (Roles role : roleList) {
                ConfigAttribute configAttribute = new SecurityConfig(role.getRoleCode());
                configAttributes.add(configAttribute);
            }
            resourceMap.put(resource.getContent(), configAttributes);
        }
        return resourceMap;
    }

    /**
     * 加载模板
     */
    @RequestMapping(value = "/loadTemplate", method = RequestMethod.POST)
    public String loadTemplate(String url) {
        return url;
    }

    /**
     * 获取拼音码
     */
    @RequestMapping(value = "/common/getpycode")
    @ResponseBody
    public String getPyCode(String hz) {
        return PyCode.getPinYinHeadChar(hz).toUpperCase();
    }
    
    /**
     * pc选择单个人员
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("/common/showuser")
    public String mcshow() throws Exception {
        String returnPage = request.getParameter("returnPage");
        String depId = request.getParameter("depId");
        if (StringUtil.isEmpty(depId)) {
            depId = "";
        }
        map.put("returnPage", returnPage);
        String uid = request.getParameter("uid");
        map.put("uid", uid);
        List<Department> depList = departmentService.findAllDepByGuid(Consts.GUID);
        map.put("depList", depList);
        // QueryResult<Users> getUsersQueryResult =
        // usersService.getUsersQueryResult((pageNo - 1) * Consts.PAGE_SIZE, pageSize,
        // "", bsMeetingInfo.getCompereUid(), bsMeetingInfo.getSponsorDid(), "",
        // Consts.GUID);
        List<Users> userList = usersService.findUsers("", depId, "", Consts.GUID);
        map.put("userList", userList);
        return "/common/depseachuser/ShowUser.html";
    }
 
    /**
     * pc选择多个人员
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("/common/showusers")
    public String meetingshow() throws Exception {
        String depId = request.getParameter("depId");
        String userIds = request.getParameter("ids");
        if (StringUtil.isEmpty(depId)) {
            depId = "";
        }
        List<Department> depList = departmentService.findAllDepByGuid(Consts.GUID);
        map.put("depList", depList);
 
        List<Users> userList = usersService.findUsers("", depId, "", Consts.GUID);
        if (!StringUtil.isEmpty(userIds)) {
            String[] user = userIds.split(",");
            for (int i = 0; i < userList.size(); i++) {
                for (int j = 0; j < user.length; j++) {
                    if (userList.get(i).getUserId().equals(user[j])) {
                        userList.get(i).setPwdConfirm("1");
                    }
                }
            }
        }
        map.put("userList", userList);
        return "/common/depseachuser/ShowUsers.html";
    }
}
